|
1
|
|
|
import { EMPTY_ARRAY } from "./consts" |
|
2
|
|
|
import type { ClassValue, Falsy } from "./defs" |
|
3
|
|
|
import { stringifyClassNamed } from "./utils" |
|
4
|
|
|
|
|
5
|
|
|
const classNameKey = "className" as const |
|
6
|
|
|
|
|
7
|
|
|
const {keys: $keys} = Object |
|
8
|
|
|
|
|
9
|
|
|
export { |
|
10
|
|
|
wrapper, |
|
11
|
|
|
truthyKeys, |
|
12
|
|
|
dehash |
|
13
|
|
|
} |
|
14
|
|
|
|
|
15
|
|
|
function wrapper<T>(className: Falsy|ClassValue, classKeys: string[], destination: T) { |
|
16
|
|
|
//@ts-expect-error |
|
17
|
|
|
destination[classNameKey] = joinWithLead(className, classKeys) |
|
18
|
|
|
|
|
19
|
|
|
return stringifyClassNamed(destination as T & {className: string}) |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
function dehash<K extends string>(source: Record<K, unknown>, keys: string[] = $keys(source)) :string[] { |
|
23
|
|
|
for (let i = keys.length; i--;) { |
|
24
|
|
|
const key = keys[i] as K |
|
25
|
|
|
, value = source[key] |
|
26
|
|
|
|
|
27
|
|
|
if (typeof value === "string") |
|
28
|
|
|
keys[i] = value |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
return keys |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
//TODO TS is not working interesting |
|
35
|
|
|
function truthyKeys<T>(source: Falsy) :T[]; |
|
36
|
|
|
function truthyKeys<T extends Record<string, unknown>>(source: Readonly<T>): ( |
|
37
|
|
|
{[K in keyof typeof source]: typeof source[K] extends Falsy ? never : K}[keyof typeof source] |
|
38
|
|
|
)[]; |
|
39
|
|
|
function truthyKeys<T>(source: T): [T]; |
|
40
|
|
|
function truthyKeys<T>(source: T) { |
|
41
|
|
|
if (source === null || typeof source !== "object") |
|
42
|
|
|
return source |
|
43
|
|
|
? [source] |
|
44
|
|
|
: EMPTY_ARRAY |
|
45
|
|
|
|
|
46
|
|
|
const filtered = ( |
|
47
|
|
|
$keys(source) as (keyof T)[] |
|
48
|
|
|
) |
|
49
|
|
|
//TODO consider `delete` and further `flat` in case of perf |
|
50
|
|
|
.filter(key => source[key]) |
|
51
|
|
|
|
|
52
|
|
|
return filtered |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
//TODO Consider undefined |
|
56
|
|
|
function joinWithLead(value: Falsy|ClassValue, arr: readonly string[]) :string { |
|
57
|
|
|
const str1 = value || "" |
|
58
|
|
|
if (!arr.length) |
|
59
|
|
|
return str1 |
|
60
|
|
|
|
|
61
|
|
|
const str2 = arr.join(" ") |
|
62
|
|
|
if (!str1) |
|
63
|
|
|
return str2 |
|
64
|
|
|
|
|
65
|
|
|
return `${str1} ${str2}` |
|
66
|
|
|
} |